<?php

namespace cms\modules\v1\models\user;

use cms\modules\common\models\Admin;
use cms\modules\v1\models\admin\AdminRole;
use cms\modules\v1\models\Common;
use common\models\Functions;
use common\models\im\Im;
use common\models\Patterns;
use common\models\Status;
use common\models\user\UserLoginStatistic;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * Class User
 * @package cms\modules\v1\models
 */
class User extends \common\models\user\User
{
    public $password;

    /**
     * 验证规则
     */
    public function rules()
    {
        return [
            #添加用户
            [['login_name', 'nick_name', 'password', 'pay_password'], 'required', 'message' => '{attribute}不能为空', 'on' => 'addUser'],

            #修改用户信息
            [['login_name', 'nick_name'], 'required', 'message' => '{attribute}不能为空', 'on' => 'editUser'],
        ];
    }

    /**
     * 设置属性名称
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'login_name' => '账号',
            'nick_name' => '账号',
            'password' => '密码',
            'pay_password' => '支付密码',
            'phone' => '手机号',
            'status' => '状态',
            'is_service' => '是否商户',
        ];
    }

    /**
     * 设置场景
     * @return array
     */
    public function scenarios()
    {
        $newScenarios = [
            'addUser' => [
                'login_name',
                'password',
                'pay_password',
                'nick_name',
            ],

            'editUser' => [
                'login_name',
                'password',
                'pay_password',
                'nick_name',
                'is_service',
            ],
        ];
        return array_merge(parent::scenarios(), $newScenarios);
    }

    /**
     * 返回列表数据
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getListData($page = 1, $size = 20)
    {
//        ini_set("memory_limit", "10240M");
        try {

            //搜索条件
            $searchWhere = $this->getSearch();//自定义搜索条件

            //排序 order
            $orderBy = $this->getOrder();


            //得到文章的总数
            $count = static::getObjectCountByAndWhere($searchWhere['where'], $searchWhere['andWhere'])->count();
            $data = static::setPageinationAPI($page, $size, $count);

            //设置分页
            $offset = ($data['page'] - 1) * $size;

            $query = static::getObjectByAndWhere($searchWhere['where'], $searchWhere['andWhere'], '*', $orderBy, $offset, $size);

            $data['data'] = $this->handelList($query);

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function getOrder()
    {
        $sort = Yii::$app->request->get('sort');

        $sort = json_decode($sort, true);

        if (empty($sort) || $sort['order'] == "normal") {
            return "id ASC";
        }
        $field = $sort['field'];

        return $field . " " . $sort['order'];

    }

    /**
     * 自定义参数的搜索  搜索,搜索也分每一列
     * 这里要根据业务逻辑进行修改
     * @return array
     */
    public function getSearch()
    {
        $where = [];
        $andWhere = [];
        $status = Yii::$app->request->get('status', '');
        $phone = Yii::$app->request->get('phone', '');
        $txCode = Yii::$app->request->get('tx_code', '');
        $code = Yii::$app->request->get('code', '');
        $startTime = Yii::$app->request->get('start', '');
        $endTime = Yii::$app->request->get('end', '');
        if ($status) {
            $where['status'] = (int)$status;
        }

        if ($txCode) {
            $where['tx_code'] = $txCode;
        }

        if ($code) {
            $where['user_code'] = $code;
        }


        if ($phone) {
            $andWhere[] = ['like', 'login_name', $phone];
        }


        if ($startTime && $endTime) {
            $andWhere[] = ['between', 'register_time', $startTime, $endTime];
        }

        return [
            'where' => $where,
            'andWhere' => $andWhere
        ];
    }

    /**
     * 处理初始化数据
     * @param $query
     * @return mixed
     */
    public function handelList($query)
    {
        if (empty($query)) {
            return null;
        }
        $list = $query->with([
            "money" => function ($q) {
                $q->select(['id', "num", "user_id"]);
            },

            "kyc" => function ($q) {
                $q->select(['user_id', "oss_url"]);
            },
        ])->asArray()->all();

        foreach ($list as &$value) {
            $money = ArrayHelper::getValue($value, "money",[]);
            $singleKycInfo = ArrayHelper::getValue($value, "kyc",[]);
            $value['money'] = floatval($money['num'] ?? ($value['money'] ?? 0));
            $value['face'] = static::getAvatar($value['user_face']);
            $value['user_sky_face'] = $singleKycInfo ? static::getImages($singleKycInfo['oss_url']) : '';
        }
        return $list;
    }

    /**
     * 添加修改
     * @return array
     */
    public function addEdit()
    {
        $trans = Yii::$app->db->beginTransaction();
        try {
            if (!$this->validate()) {
                throw new Exception($this->getErrorSummary(true)[0]);
            }

            $post = Yii::$app->request->post();
            $id = isset($post['id']) && !empty($post['id']) ? intval($post['id']) : 0;
            $data = [];
            $data = array_merge($data, $this->getSaveData($this->scenario, $post));

            $data['phone'] = $data['login_name'];

            if ($post['pay_password']) {
                //修改密码
                $data['pay_password'] = Yii::$app->security->generatePasswordHash($post['pay_password']);
            }

            if ($post['password']) {
                //修改密码
                $data['password_hash'] = Yii::$app->security->generatePasswordHash($post['password']);
            }

            if (!empty($id)) {
                //更新操作
                $user = static::getOneInfoById($id);

                $data['update_time'] = date('Y-m-d H:i:s');

                $res = static::updateDataWithLog($data, ['id' => $id]);
                if ($res === false) {
                    throw new Exception('系统错误，请联系开发小哥哥~~');
                }

            } else {
                //添加操作
                $data['register_time'] = date('Y-m-d H:i:s');

                if (empty($data['pay_password'])) {
                    throw new Exception("请设置支付密码");
                }
                if (empty($data['password_hash'])) {
                    throw new Exception("请设置密码");
                }
                $where = [
                    "login_name" => $data['login_name']
                ];
                $chk = static::getOneByWhere($where);
                if (!empty($chk)) {
                    throw new Exception('该手机号已存在，无法添加');
                }

                $data['parent_id'] = 0;
                $data['parent_path'] = '0,';
                $data['is_kyc'] = (int)$post['is_kyc'];
                $data['invite_code'] = $this->_createInviteCode();
                $data['nick_name'] = $this->_createNickname();

                $res = static::insertDataWithLog($data);
                if ($res === false) {
                    throw new Exception('系统错误，请联系开发小哥哥~~');
                }
                $data['id'] = $res;
                $imUser = $this->createImUser($data);
            }


            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    // 批量添加账号
    public function multipleAdd()
    {
        try {
            $post = Yii::$app->request->post();
            $phones = $post['login_name'];
            $error = $success = [];


            if (empty($post['pay_password'])) {
                throw new Exception("请设置支付密码");
            }
            if (empty($post['password'])) {
                throw new Exception("请设置密码");
            }

            if (empty($phones)) {
                throw new Exception('请添加手机号');
            }

            $phonesStr = trim($phones);
            $phonesStr = str_replace("，", ",", $phonesStr);
            $phonesArr = explode(",", $phonesStr);
            if (count($phonesArr) > 20) {
                throw new Exception('每次只能添加20个手机号');
            }

            $phonesArr = array_unique($phonesArr);
            foreach ($phonesArr as $v) {
                $v = trim($v);
                $where = [];
                $where = [
                    "login_name" => $v
                ];
                $chk = static::getOneByWhere($where);
                if (!empty($chk)) {
                    $error[] = $v;
                    continue;
                }

                if (!preg_match(Patterns::phoneNumber(), $v)) {
                    $error[] = $v;
                    continue;
                }

                $trans = Yii::$app->db->beginTransaction();
                try {
                    $this->addOne(
                        $v,
                        $post['password'],
                        $post['pay_password']
                    );
                    $success[] = $v;
                    $trans->commit();

                } catch (Exception $e) {
                    $error[] = $v;
                    $trans->rollBack();
                }
            }

            $count = count($error);
            $countSuccess = count($success);
            return Functions::formatRestAPI(0, "添加成功{$countSuccess}个, 失败{$count}个");
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function addOne($loginName = 0, $pass = '', $payPwd = '')
    {
        //添加操作
        $data['register_time'] = date('Y-m-d H:i:s');

        $where = [
            "login_name" => $loginName
        ];
        $chk = static::getOneByWhere($where);
        if (!empty($chk)) {
            throw new Exception('该手机号已存在，无法添加');
        }

        $data['login_name'] = $loginName;
        $data['nick_name'] = $this->_createNickname();
        $data['invite_code'] = $this->_createInviteCode();
        $data['parent_path'] = "0,";
        $data['password_hash'] = Yii::$app->security->generatePasswordHash($pass);
        $data['pay_password'] = Yii::$app->security->generatePasswordHash($payPwd);
        $res = static::insertDataWithLog($data);
        if ($res === false) {
            throw new Exception('系统错误，请联系开发小哥哥~~');
        }
        $data['id'] = $res;
        $this->createImUser($data);

    }

    /**
     * 获取修改信息
     * @param int $id
     * @return array
     */
    public function getInfo($id = 0)
    {
        try {
            $id = (int)$id;

            if (empty($id)) {
                throw new Exception('未知信息');
            }
            $info = static::getOneInfoById($id);
            if (empty($info)) {
                throw new Exception('信息不存在');
            }

            return Functions::formatRestAPI(0, '', $info);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    //客户一周注册表
    public function weekRegister()
    {
        try {
            $adminInfo = (new Admin())->checkLogin();

            if ($adminInfo['role_type'] != 1) {
                $role = AdminRole::getOneInfoById($adminInfo['role_type']);
                $type = explode(',',$role['role_permissions']);
                if(!in_array(1,$type)){
                    throw new Exception('无访问权限');
                }
            }

            $days = 30;
            $date = time() - 24 * 3600 * $days;
            $data = [];

            for ($i = 1; $i <= $days; $i++) {
                $currDate = strval(date("Y-m-d", $date + $i * 24 * 3600));
                $registerNum = $this->getRegisterNum($currDate);
                $data[] = [$currDate, $registerNum];
            }

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


    /**
     * 启用禁用 等切换装填
     * @return array
     */
    public function setField()
    {
        try {
            $post = Yii::$app->request->post();

            $id = $post['id'];
            if (empty($id)) {
                throw new Exception('未知信息');
            }

            if (!empty($post['status'])) {
                $data['status'] = (int)$post['status'];
                if ($data['status'] == Status::COMMON_RADIO_NO) {
                    $userInfo = static::getOneInfoById($id);
                    $res = (new Im()) ->loginOut($userInfo['tx_code']);
                    if (!$res) {
                        throw new Exception('禁用失败');
                    }
                }
            }

            $data['update_time'] = date("Y-m-d H:i:s");
            $res = static::updateData($data, ['id' => $id]);
            if ($res === false) {
                throw new Exception('操作失败');
            }
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }



    /**
     * 获取map信息
     * @return array
     */
    public function getSelectMap()
    {
        $where['status'] = Status::COMMON_STATUS_SHOW;
        $list = static::getByWhere($where);
        $result = [];
        foreach ($list as $key => $value) {
            $authName = $value['auth_name'] ?: '未实名';
            $result[$value['id']] = $value['login_name'] . '-' . $authName;
        }
        return Functions::formatRestAPI(0, '', $result);
    }


    public function cleanUser()
    {
        try {
            $post = Yii::$app->request->post();
            $id = isset($post['id']) ? $post['id'] : 0;

            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $info = UserLoginStatistic::getOneInfoById($id);
            $phones = explode(",", $info['phone']);
            $userList = static::getByWhere(['login_name' => $phones], ["id", "status","login_name","tx_code"]);

            if ($userList) {
                foreach ($userList as $key => $v) {
                    if ($v['status'] == Status::COMMON_RADIO_NO) {
                        continue;
                    }
                    $updateData = [];
                    $updateData['status'] = Status::COMMON_RADIO_NO;

                    $trans = Yii::$app->db->beginTransaction();
                    try {
                        $res = static::updateData($updateData,['id' => $v['id']]);
                        if ($res === false) {
                            throw new Exception("{$v['login_name']}禁用失败");
                        }

                        $resIm = (new Im()) ->loginOut($v['tx_code']);
                        if (!$resIm) {
                            throw new Exception("{$v['login_name']}禁用失败");
                        }
                        $trans->commit();
                    } catch (Exception $e) {
                        $trans->rollBack();
                    }

                }
            }
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }
}
